<?php

namespace app\admin\logic\Order;

use app\admin\model\Warehouse as WarehouseModel;
use app\admin\model\Inventory as InventoryModel;


class Index
{
    public function getInventory($param)
    {
        $where = [
            ['productid', '=', $param['productid']],
            ['is_futures', '=', 0],
            ['is_del', '=', 0],
        ];

        $warehouse = WarehouseModel::where('id', '=', $param['wid'])->field('fl_warehouse_id')->find();

        if ($warehouse && $warehouse['fl_warehouse_id'] != null) {
            $where[] = ['wid', '=', $param['wid']];
        } else {

            $warehouse_ids = WarehouseModel::where('fl_warehouse_id', '=', $param['wid'])->column('id');
            $where[] = ['wid', 'in', $warehouse_ids];
        }
        $oInventoryModel = InventoryModel::where($where)
            ->with('warehouse')
            ->whereRaw('(available_qty - lock_qty) > ?', [0])
            ->field([
                'id',
                'available_qty - lock_qty as available_qty',
                'inbound_batch',
                'create_time',
                'productid',
                'arrival_date',
                'is_futures',
                'wid',
                'is_sale',
                'inbound_batch'
            ])
            ->order('available_qty desc , create_time desc')
            ->select();
        $data = [];
        foreach ($oInventoryModel as $value) {
            $data[] = [
                'id' => $value['id'],
                'available_qty' => $value['available_qty'],
                'create_time' => $value['create_time'],
                'productid' => $value['productid'],
                'arrival_date' => $value['arrival_date'],
                'is_futures' => $value['is_futures'],
                'wid' => $value['wid'],
                'warehouse_name' => $value['warehouse']['name'],
                'is_sale' => $value['is_sale'],
                'inbound_batch' => $value['inbound_batch']
            ];
        }
        return ['code' => 0, 'message' => 'success', 'data' => $data];
    }
}
